package com.baiye.www.proxyHandler;

import com.baiye.www.message.RpcResponseMessage;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.concurrent.Promise;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author baiye
 * @version 1.0
 * @date 2021/12/2 15:01
 */
@Slf4j
@ChannelHandler.Sharable
public class RpcResponseMessageHandler extends SimpleChannelInboundHandler<RpcResponseMessage> {

    public static final Map<Long, Promise<Object>> PROMISE_MAP=new ConcurrentHashMap<>();

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, RpcResponseMessage rpcResponseMessage) throws Exception {
        Promise<Object> promise = PROMISE_MAP.remove(rpcResponseMessage.getSequenceId());
            if(promise!=null){
                Object result = rpcResponseMessage.getResult();
                Exception exception = rpcResponseMessage.getException();
                if(exception==null){
                    promise.setSuccess(result);
                }else {
                    promise.setFailure(exception);
                }
            }
    }
}
